package com.kurumi.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kurumi.pojo.MedicalRecordPageTrace;
import com.kurumi.pojo.MedicalRecordTrace;
import com.kurumi.pojo.RespondResult;
import com.kurumi.query.MedicalRecordQuery;
import com.kurumi.service.MedicalRecordService;
import com.kurumi.service.MedicalRecordTraceService;
import com.kurumi.util.CSVUtils;
import com.kurumi.util.DateUtil;
import com.kurumi.util.ExcelUtils;
import com.kurumi.util.JavaDBFUtils;

@Controller
@RequestMapping("/medical_record_trace")
public class MedicalRecordTraceController {

	@Autowired
	private MedicalRecordTraceService medicalRecordTraceService;
	
	@Autowired
	private MedicalRecordService medicalRecordService;
	
	@GetMapping("/query_page_trace")
	public String queryPageTrace(){
		return "trace/query_page_trace";
	}
	@GetMapping("/query_page_quality_control_trace")
	public String queryPageQualityControlTrace(){
		return "trace/query_page_quality_control_trace";
	}
	
	@GetMapping("/query_page_coding_trace")
	public String queryPageCodingTrace(){
		return "trace/query_page_coding_trace";
	}
	@GetMapping("/query_page_scan_trace")
	public String queryPageScanTrace(){
		return "trace/query_page_scan_trace";
	}
	@GetMapping("/query_page_putaway_trace")
	public String queryPagePutawayTrace(){
		return "trace/query_page_putaway_trace";
	}
	
	@GetMapping("/ajax_query_page_trace")
	@ResponseBody
	public RespondResult ajaxQueryPageTrace(MedicalRecordQuery params){
		RespondResult respondResult = null;
		
		try{
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			int count = 0;
			if(!params.queryUnEncodingEmpty()){
				medicalRecords = medicalRecordTraceService.getMedicalRecordOfPageTrace(params);
				count= medicalRecordTraceService.getMedicalRecordCountOfPageTrace(params);
			}
			
			params.setTotalCounts(count);
			params.setQueryDatas(medicalRecords);
			respondResult = new RespondResult(true, RespondResult.successCode, null, params);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), params);
		}
		
		return respondResult;
	}
	
	@GetMapping("/ajax_page_trace_detail")
	@ResponseBody
	public RespondResult ajaxPageTraceDetail(String visitGuid){
		RespondResult respondResult = null;
		Map<String,Object> data = new HashMap<String, Object>();
		try{
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			
			medicalRecords = medicalRecordService.getMedicalRecordByVisitGuid(visitGuid);
			data.put("medicalRecords", medicalRecords);
			List<Map<String,Object>> medicalRecordTraces = new ArrayList<Map<String,Object>>();
			medicalRecordTraces = medicalRecordTraceService.getMeditalRecordPageTraceByVisitGuid(visitGuid);
			data.put("medicalRecordTraces", medicalRecordTraces);
			respondResult = new RespondResult(true, RespondResult.successCode, null, data);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), null);
		}
		
		return respondResult;
	}
	
	
	@PostMapping("/ajax_add_medical_record_trace")
	@ResponseBody
	public RespondResult ajaxAddMedicalRecordTrace(MedicalRecordTrace medicalRecordTrace){
		RespondResult respondResult = null;
		
		try{
			int count = medicalRecordTraceService.insertMedicalRecordTrace(medicalRecordTrace);
			if(count == 1){
				respondResult = new RespondResult(true, RespondResult.successCode, "添加成功", "添加成功");
			}else{
				respondResult = new RespondResult(true, RespondResult.errorCode, "添加失败", "添加失败");
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	
	@GetMapping("/ajax_query_page_putaway_trace")
	@ResponseBody
	public RespondResult ajaxQueryPagePutAwayTrace(MedicalRecordQuery params){
		RespondResult respondResult = null;
		
		try{
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			int count = 0;
			if(!params.queryUnEncodingEmpty()){
				medicalRecords = medicalRecordTraceService.getMedicalRecordOfPagePutAwayTrace(params);
				count= medicalRecordTraceService.getMedicalRecordCountOfPagePutAwayTrace(params);
			}
			
			params.setTotalCounts(count);
			params.setQueryDatas(medicalRecords);
			respondResult = new RespondResult(true, RespondResult.successCode, null, params);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), params);
		}
		
		return respondResult;
	}
	
	@PostMapping("/ajax_add_page_quality_control_trace")
	@ResponseBody
	public RespondResult ajaxAddPageQualityControlTrace(String visitGuid){
		RespondResult respondResult = null;
		
		try{
			Subject subject=SecurityUtils.getSubject();
			Session session = subject.getSession();
			Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
			String userCode =(String)currentUser.get("user_code");
			String userName =(String)currentUser.get("user_name");
			MedicalRecordPageTrace putwayPageTrace = new MedicalRecordPageTrace();
			
			putwayPageTrace.setVisitGuid(visitGuid);
			putwayPageTrace.setCreateUserId(userCode);
			putwayPageTrace.setCreateUserName(userName);
			putwayPageTrace.setTraceTypeCode(MedicalRecordPageTrace.VISIT_QUALITY);
			putwayPageTrace.setTraceTypeName(MedicalRecordPageTrace.VISIT_QUALITY_NAME);
			putwayPageTrace.setTraceDateTime(new Date());
			int count = medicalRecordTraceService.insertMedicalRecordPageTrace(putwayPageTrace);
			if(count == 1){
				respondResult = new RespondResult(true, RespondResult.successCode, "质控示踪成功", "质控示踪成功");
			}else{
				respondResult = new RespondResult(true, RespondResult.errorCode, "质控示踪失败", "质控示踪失败");
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}

	
	@PostMapping("/ajax_add_page_coding_trace")
	@ResponseBody
	public RespondResult ajaxAddPageCodingTrace(String visitGuid){
		RespondResult respondResult = null;
		
		try{
			Subject subject=SecurityUtils.getSubject();
			Session session = subject.getSession();
			Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
			String userCode =(String)currentUser.get("user_code");
			String userName =(String)currentUser.get("user_name");
			MedicalRecordPageTrace putwayPageTrace = new MedicalRecordPageTrace();
			
			putwayPageTrace.setVisitGuid(visitGuid);
			putwayPageTrace.setCreateUserId(userCode);
			putwayPageTrace.setCreateUserName(userName);
			putwayPageTrace.setTraceTypeCode(MedicalRecordPageTrace.VISIT_CODING);
			putwayPageTrace.setTraceTypeName(MedicalRecordPageTrace.VISIT_CODING_NAME);
			putwayPageTrace.setTraceDateTime(new Date());
			int count = medicalRecordTraceService.insertMedicalRecordPageTrace(putwayPageTrace);
			if(count == 1){
				respondResult = new RespondResult(true, RespondResult.successCode, "编码示踪成功", "编码示踪成功");
			}else{
				respondResult = new RespondResult(true, RespondResult.errorCode, "编码示踪失败", "编码示踪失败");
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}

	@PostMapping("/ajax_add_page_scan_trace")
	@ResponseBody
	public RespondResult ajaxAddPageScanTrace(String visitGuid){
		RespondResult respondResult = null;
		
		try{
			Subject subject=SecurityUtils.getSubject();
			Session session = subject.getSession();
			Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
			String userCode =(String)currentUser.get("user_code");
			String userName =(String)currentUser.get("user_name");
			MedicalRecordPageTrace putwayPageTrace = new MedicalRecordPageTrace();
			
			putwayPageTrace.setVisitGuid(visitGuid);
			putwayPageTrace.setCreateUserId(userCode);
			putwayPageTrace.setCreateUserName(userName);
			putwayPageTrace.setTraceTypeCode(MedicalRecordPageTrace.VISIT_SCAN);
			putwayPageTrace.setTraceTypeName(MedicalRecordPageTrace.VISIT_SCAN_NAME);
			putwayPageTrace.setTraceDateTime(new Date());
			int count = medicalRecordTraceService.insertMedicalRecordPageTrace(putwayPageTrace);
			if(count == 1){
				respondResult = new RespondResult(true, RespondResult.successCode, "扫描示踪成功", "扫描示踪成功");
			}else{
				respondResult = new RespondResult(true, RespondResult.errorCode, "扫描示踪失败", "扫描示踪失败");
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	
	@PostMapping("/ajax_add_page_putaway_trace")
	@ResponseBody
	public RespondResult ajaxAddPagePutawayTrace(String visitGuid){
		RespondResult respondResult = null;
		
		try{
			Subject subject=SecurityUtils.getSubject();
			Session session = subject.getSession();
			Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
			String userCode =(String)currentUser.get("user_code");
			String userName =(String)currentUser.get("user_name");
			MedicalRecordPageTrace putwayPageTrace = new MedicalRecordPageTrace();
			
			putwayPageTrace.setVisitGuid(visitGuid);
			putwayPageTrace.setCreateUserId(userCode);
			putwayPageTrace.setCreateUserName(userName);
			putwayPageTrace.setTraceTypeCode(MedicalRecordPageTrace.VISIT_PIGEONHOLE);
			putwayPageTrace.setTraceTypeName(MedicalRecordPageTrace.VISIT_PIGEONHOLE_NAME);
			putwayPageTrace.setTraceDateTime(new Date());
			int count = medicalRecordTraceService.insertMedicalRecordPageTrace(putwayPageTrace);
			if(count == 1){
				respondResult = new RespondResult(true, RespondResult.successCode, "归档成功", "归档成功");
			}else{
				respondResult = new RespondResult(true, RespondResult.errorCode, "归档失败", "归档失败");
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	
	@GetMapping("/ajax_query_page_trace_scan")
	@ResponseBody
	public RespondResult ajaxQueryPageTraceScan(MedicalRecordQuery params){
		RespondResult respondResult = null;
		
		try{
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			int count = 0;
			if(!params.querySignedEmpty()){
				medicalRecords = medicalRecordTraceService.getMedicalRecordOfScan(params);
				count= medicalRecordTraceService.getMedicalRecordCountOfScan(params);
			}
			
			params.setTotalCounts(count);
			params.setQueryDatas(medicalRecords);
			respondResult = new RespondResult(true, RespondResult.successCode, null, params);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), params);
		}
		
		return respondResult;
	}
	
	@GetMapping("/export_scan_medical_record_csv")
	public void exportScanMedicalRecordCSV(MedicalRecordQuery params,String beyondDay,HttpServletResponse response) {
		OutputStream out = null;
		try{
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			if(!params.querySignedEmpty()){
				params.setPageSize(null);
				medicalRecords = medicalRecordTraceService.getMedicalRecordOfScan(params);
			}
			/*response.setContentType("octets/stream");*/
			/*response.setCharacterEncoding("GBK");*/
			response.setContentType("applicationnd.ms-excel");
			String title= "病案扫描交接";
			StringBuilder downLoadFileName = new StringBuilder();
			downLoadFileName = new StringBuilder(
					"attachment;filename=");
			downLoadFileName.append(title).append(DateUtil.dateFormat(new Date()))
					.append(".csv");
			String encodeStr = new String(downLoadFileName.toString().getBytes(
					"GB2312"), "ISO_8859_1");
			response.addHeader("Content-Disposition", encodeStr);
			out = response.getOutputStream();
			List<String> headers = new ArrayList<String>();
			headers.add("住院号");/*
			header.add("病案号");
			header.add("住院次数");*/
			headers.add("姓名");
			headers.add("科别");
			headers.add("出院日期");
			List<String> keys = new ArrayList<String>();
			keys.add("only_id");
			keys.add("patient_name");
			keys.add("out_dept_name");
			keys.add("out_hospital_date");
			List<List<String>> records = new ArrayList<List<String>>();
			for (Map<String, Object> medicalRecord : medicalRecords) {
				List<String> record = new ArrayList<String>();
				record.add((String)medicalRecord.get("only_id"));
				record.add((String)medicalRecord.get("patient_name"));
				record.add((String)medicalRecord.get("out_dept_name"));
				record.add((String)medicalRecord.get("out_hospital_date"));
				records.add(record);
			}
			CSVUtils.csvWriter(out, headers, records);
			
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			if(out != null){
				try {
					out.flush();
				} catch (Exception e2) {
					// TODO: handle exception
				}
				try {
					out.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			
		}
		
	}
	
	
	@GetMapping("/export_scan_medical_record_xls")
	public void exportScanMedicalRecordXLS(MedicalRecordQuery params,String beyondDay,HttpServletResponse response) {
		OutputStream out = null;
		try{
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			if(!params.querySignedEmpty()){
				params.setPageSize(null);
				medicalRecords = medicalRecordTraceService.getMedicalRecordOfScan(params);
			}
			/*response.setContentType("octets/stream");*/
			/*response.setCharacterEncoding("GBK");*/
			response.setContentType("applicationnd.ms-excel");
			String title= "病案扫描交接"+DateUtil.dateFormat(new Date());
			StringBuilder downLoadFileName = new StringBuilder();
			downLoadFileName = new StringBuilder(
					"attachment;filename=");
			downLoadFileName.append(title)
					.append(".xls");
			/*downLoadFileName.append(title).append(DateUtil.dateFormat(new Date()))
			.append(".dbf");*/
			String encodeStr = new String(downLoadFileName.toString().getBytes(
					"GB2312"), "ISO_8859_1");
			response.addHeader("Content-Disposition", encodeStr);
			out = response.getOutputStream();
			List<String> headers = new ArrayList<String>();
			headers.add("住院号");/*
			header.add("病案号");
			header.add("住院次数");*/
			headers.add("姓名");
			headers.add("科别");
			headers.add("出院日期");
			List<String> keys = new ArrayList<String>();
			keys.add("only_id");
			keys.add("patient_name");
			keys.add("out_dept_name");
			keys.add("out_hospital_date");
			
			List<Map<String, String>> records = new ArrayList<Map<String,String>>();
			for (Map<String, Object> medicalRecord : medicalRecords) {
				Map<String, String> record = new HashMap<String, String>();
				record.put("only_id",(String)medicalRecord.get("only_id"));
				record.put("patient_name",(String)medicalRecord.get("patient_name"));
				record.put("out_dept_name",(String)medicalRecord.get("out_dept_name"));
				record.put("out_hospital_date",(String)medicalRecord.get("out_hospital_date"));
				records.add(record);
			}
			ExcelUtils.exportExcel(out, title, headers, keys, records);
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			if(out != null){
				try {
					out.flush();
				} catch (Exception e2) {
					// TODO: handle exception
				}
				try {
					out.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			
		}
		
	}
	
}
